﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Dts.Runtime;

namespace ToddMcDermid.SSIS
{
    public partial class SendHTMLMailTaskEditor : Form
    {
        #region Private Variables
        private TaskHost _taskHost;
        private Connections _connections;
        #endregion

        #region Constructor
        public SendHTMLMailTaskEditor(TaskHost taskHost, Connections connections)
        {
            InitializeComponent();

            this._taskHost = taskHost;
            this._connections = connections;
        }
        #endregion

        #region Form Event Handlers
        private void EmptyTaskWithUIEditor_Load(object sender, EventArgs e)
        {
            try
            {
                #region Load Connection Managers
                this.cboSMTPConnectionManager.Items.Clear();
                this.cboSMTPConnectionManager.DisplayMember = "Name";
                this.cboSMTPConnectionManager.ValueMember = "ID";
                string connectionName = null;
                string connectionID = null;
                object propertyConnectionManagerID = this._taskHost.Properties["SmtpConnectionManagerID"].GetValue(this._taskHost);
                if (propertyConnectionManagerID != null) 
                {
                    connectionID = (string)propertyConnectionManagerID;
                }
                foreach (ConnectionManager connection in this._connections)
                {
                    if (connection.CreationName == "SMTP")
                    {
                        this.cboSMTPConnectionManager.Items.Add(connection.Name);
                        if ((propertyConnectionManagerID != null) && (connection.ID == connectionID))
                        {
                            connectionName = connection.Name;
                        }
                    }
                }
                this.cboSMTPConnectionManager.SelectedItem = connectionName;
                #endregion

                #region From Address
                object propertyFromAddress = this._taskHost.Properties["FromAddress"].GetValue(this._taskHost);
                if (propertyFromAddress != null)
                {
                    this.txtFromAddress.Text = (string)propertyFromAddress;
                }
                #endregion

                #region ReplyTo Address
                object propertyReplyToAddress = this._taskHost.Properties["ReplyToAddress"].GetValue(this._taskHost);
                if (propertyReplyToAddress != null)
                {
                    this.txtReplyToAddress.Text = (string)propertyReplyToAddress;
                }
                #endregion

                #region To Addresses
                object propertyToAddress = this._taskHost.Properties["ToAddresses"].GetValue(this._taskHost);
                if (propertyToAddress != null)
                {
                    this.txtToAddresses.Text = (string)propertyToAddress;
                }
                #endregion

                #region CC Addresses
                object propertyCCAddress = this._taskHost.Properties["CCAddresses"].GetValue(this._taskHost);
                if (propertyCCAddress != null)
                {
                    this.txtCCAddresses.Text = (string)propertyCCAddress;
                }
                #endregion
 
                #region BCC Addresses
                object propertyBCCAddress = this._taskHost.Properties["BCCAddresses"].GetValue(this._taskHost);
                if (propertyBCCAddress != null)
                {
                    this.txtBCCAddresses.Text = (string)propertyBCCAddress;
                }
                #endregion

                #region Subject
                object propertySubject = this._taskHost.Properties["Subject"].GetValue(this._taskHost);
                if (propertySubject != null)
                {
                    this.txtSubject.Text = (string)propertySubject;
                }
                #endregion

                #region Body Content
                this.cboBodyContent.Items.Clear();
                foreach (string bodyContentType in Enum.GetNames(typeof(SendHTMLMailTask.BodyContentType)))
                {
                    this.cboBodyContent.Items.Add(bodyContentType);
                }
                object propertyBodyContent = this._taskHost.Properties["BodyContent"].GetValue(this._taskHost);
                if (propertyBodyContent != null)
                {
                    SendHTMLMailTask.BodyContentType bodyContent = (SendHTMLMailTask.BodyContentType)propertyBodyContent;
                    this.cboBodyContent.SelectedItem = bodyContent.ToString();
                }
                #endregion

                #region Body Source
                this.cboBodySource.Items.Clear();
                foreach (string bodySourceType in Enum.GetNames(typeof(SendHTMLMailTask.BodySourceType)))
                {
                    this.cboBodySource.Items.Add(bodySourceType);
                }
                object propertyBodySource = this._taskHost.Properties["BodySource"].GetValue(this._taskHost);
                if (propertyBodySource != null)
                {
                    SendHTMLMailTask.BodySourceType bodySource = (SendHTMLMailTask.BodySourceType)propertyBodySource;
                    this.cboBodySource.SelectedItem = bodySource.ToString();
                }
                #endregion

                #region Body
                this.cboVariableBody.Items.Clear();
                foreach (Variable possibleVariable in this._taskHost.Variables)
                {
                    if ((possibleVariable.DataType == TypeCode.String) && (!possibleVariable.SystemVariable))
                    {
                        this.cboVariableBody.Items.Add(possibleVariable.QualifiedName);
                    }
                }
                object propertyBody = this._taskHost.Properties["Body"].GetValue(this._taskHost);
                if (propertyBody != null)
                {
                    if (this.GetSelectedBodySourceType() == SendHTMLMailTask.BodySourceType.Direct)
                    {
                        if (this.GetSelectedBodyContentType() == SendHTMLMailTask.BodyContentType.HTML)
                        {
                            this.txtHTMLBody.Text = (string)propertyBody;
                            this.txtPlaintextBody.Visible = false;
                        }
                        else
                        {
                            this.txtPlaintextBody.Text = (string)propertyBody;
                            this.tabBody.Visible = false;
                        }
                    }
                    else
                    {
                        this.cboVariableBody.SelectedItem = (string)propertyBody;
                    }
                }
                #endregion

                #region Attachments
                this.lbxAttachments.Items.Clear();
                object propertyAttachments = this._taskHost.Properties["Attachments"].GetValue(this._taskHost);
                if (propertyAttachments != null)
                {
                    string attachmentList = (string)propertyAttachments;
                    if (attachmentList.Length > 0)
                    {
                        string[] attachments = attachmentList.Split(';');
                        foreach (string attachment in attachments)
                        {
                            this.lbxAttachments.Items.Add(attachment);
                        }
                    }
                }
                #endregion

                #region Priority
                this.cboPriority.Items.Clear();
                foreach (string priority in Enum.GetNames(typeof(System.Net.Mail.MailPriority)))
                {
                    this.cboPriority.Items.Add(priority);
                }
                object propertyPriority = this._taskHost.Properties["Priority"].GetValue(this._taskHost);
                if (propertyPriority != null)
                {
                    System.Net.Mail.MailPriority priority = (System.Net.Mail.MailPriority)propertyPriority;
                    this.cboPriority.SelectedItem = priority.ToString();
                }
                #endregion
            }
            #region catch ...
            catch
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    System.Diagnostics.Debugger.Break();
                }
            }
            #endregion
        }
        #endregion

        #region Control Event Handlers
        #region btnOK_Click
        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                #region Connection Manager
                string connectionName = (string)this.cboSMTPConnectionManager.SelectedItem;
                if (connectionName != null)
                {
                    string connectionID = null;
                    foreach (ConnectionManager connection in this._connections)
                    {
                        if (connection.Name == connectionName)
                        {
                            connectionID = connection.ID;
                            break;
                        }
                    }
                    this._taskHost.Properties["SmtpConnectionManagerID"].SetValue(this._taskHost, connectionID);
                }
                #endregion

                #region From Address
                this._taskHost.Properties["FromAddress"].SetValue(this._taskHost, this.txtFromAddress.Text);
                #endregion

                #region ReplyTo Address
                this._taskHost.Properties["ReplyToAddress"].SetValue(this._taskHost, this.txtReplyToAddress.Text);
                #endregion

                #region To Addresses
                this._taskHost.Properties["ToAddresses"].SetValue(this._taskHost, this.txtToAddresses.Text);
                #endregion

                #region CC Addresses
                this._taskHost.Properties["CCAddresses"].SetValue(this._taskHost, this.txtCCAddresses.Text);
                #endregion

                #region BCC Addresses
                this._taskHost.Properties["CCAddresses"].SetValue(this._taskHost, this.txtCCAddresses.Text);
                #endregion

                #region Subject
                this._taskHost.Properties["Subject"].SetValue(this._taskHost, this.txtSubject.Text);
                #endregion

                #region Body Content
                this._taskHost.Properties["BodyContent"].SetValue(this._taskHost, this.GetSelectedBodyContentType());
                #endregion

                #region Body Source
                this._taskHost.Properties["BodySource"].SetValue(this._taskHost, this.GetSelectedBodySourceType());
                #endregion

                #region Body
                if (this.GetSelectedBodySourceType() == SendHTMLMailTask.BodySourceType.Direct)
                {
                    if (this.GetSelectedBodyContentType() == SendHTMLMailTask.BodyContentType.HTML)
                    {
                        this._taskHost.Properties["Body"].SetValue(this._taskHost, this.txtHTMLBody.Text);
                    }
                    else
                    {
                        this._taskHost.Properties["Body"].SetValue(this._taskHost, this.txtPlaintextBody.Text);
                    }
                }
                else
                {
                    this._taskHost.Properties["Body"].SetValue(this._taskHost, this.cboVariableBody.SelectedItem);
                }
                #endregion

                #region Attachments
                string attachmentList = "";
                foreach (object attachmentObject in this.lbxAttachments.Items)
                {
                    if (attachmentList.Length > 0)
                    {
                        attachmentList += ";";
                    }
                    attachmentList += (string)attachmentObject;
                }
                this._taskHost.Properties["Attachments"].SetValue(this._taskHost, attachmentList);
                #endregion

                #region Body Content
                this._taskHost.Properties["Priority"].SetValue(this._taskHost, Enum.Parse(typeof(System.Net.Mail.MailPriority), (string)this.cboPriority.SelectedItem));
                #endregion

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            #region catch ...
            catch
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    System.Diagnostics.Debugger.Break();
                }
            }
            #endregion
        }
        #endregion

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void bodyConfigChanged(object sender, EventArgs e)
        {
            if (this.GetSelectedBodySourceType() == SendHTMLMailTask.BodySourceType.Direct)
            {
                this.cboVariableBody.Visible = false;
                if (this.GetSelectedBodyContentType() == SendHTMLMailTask.BodyContentType.HTML)
                {
                    this.txtPlaintextBody.Visible = false;
                    this.tabBody.Visible = true;
                    this.tabBody.SelectedTab = this.tpgCompose;
                }
                else
                {
                    this.tabBody.Visible = false;
                    this.txtPlaintextBody.Visible = true;
                }
            }
            else
            {
                this.cboVariableBody.Visible = true;
                this.txtPlaintextBody.Visible = false;
                this.tabBody.Visible = false;
            }
        }

        private void tabBody_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabBody.SelectedTab == this.tpgPreview)
            {
                string tempFile = System.IO.Path.GetTempFileName();
                if ((SendHTMLMailTask.BodyContentType)Enum.Parse(typeof(SendHTMLMailTask.BodyContentType), (string)this.cboBodyContent.SelectedItem) == SendHTMLMailTask.BodyContentType.HTML)
                {
                    tempFile = System.IO.Path.ChangeExtension(tempFile, "html");
                }
                System.IO.StreamWriter tempFileWriter = System.IO.File.CreateText(tempFile);
                tempFileWriter.Write(this.txtHTMLBody.Text);
                tempFileWriter.Close();
                this.wbrPreview.Navigate(new Uri("file://" + tempFile));
            }
        }

        private void btnAddAttachment_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog openFile = new OpenFileDialog();

            DialogResult openFileResult = openFile.ShowDialog();

            if (openFileResult == DialogResult.OK)
            {
                this.lbxAttachments.Items.Add(openFile.FileName);
            }
        }

        private void btnRemoveAttachment_Click(object sender, EventArgs e)
        {
            if (this.lbxAttachments.SelectedIndex >= 0)
            {
                this.lbxAttachments.Items.RemoveAt(this.lbxAttachments.SelectedIndex);
            }
        }
        #endregion

        #region Utilities
        private SendHTMLMailTask.BodyContentType GetSelectedBodyContentType()
        {
            SendHTMLMailTask.BodyContentType selectedBodyContentType = SendHTMLMailTask.BodyContentType.HTML;

            if (this.cboBodyContent.SelectedIndex >= 0)
            {
                selectedBodyContentType = ((SendHTMLMailTask.BodyContentType)Enum.Parse(typeof(SendHTMLMailTask.BodyContentType), (string)this.cboBodyContent.SelectedItem));
            }

            return selectedBodyContentType;
        }

        private SendHTMLMailTask.BodySourceType GetSelectedBodySourceType()
        {
            SendHTMLMailTask.BodySourceType selectedBodySourceType = SendHTMLMailTask.BodySourceType.Direct;

            if (this.cboBodySource.SelectedIndex >= 0)
            {
                selectedBodySourceType = ((SendHTMLMailTask.BodySourceType)Enum.Parse(typeof(SendHTMLMailTask.BodySourceType), (string)this.cboBodySource.SelectedItem));
            }

            return selectedBodySourceType;
        }
        #endregion
    }
}
